package service

import (
	"singo/model"
	"singo/serializer"
	"strings"
	"time"

	"github.com/rs/xid"
)

// TaskCreateService 管理新增任务的服务
type TaskCreateService struct {
	Name       string   `form:"name" json:"name" binding:"required"`
	ProjectID  string   `form:"project_id" json:"project_id"`
	Intro      string   `form:"intro" json:"intro"`
	Status     uint     `form:"status" json:"status"`
	Progress   int      `form:"progress" json:"progress"`
	Weight     float64  `form:"weight" json:"weight" binding:"required"`
	Priority   uint     `form:"priority" json:"priority"`
	ExecuteBy  []string `form:"execute_by" json:"execute_by" binding:"required"`
	ReviewBy   string   `form:"review_by" json:"review_by"`
	StartAt    string   `form:"start_at" json:"start_at"`
	DeadlineAt string   `form:"deadline_at" json:"deadline_at" binding:"required"`
	CompleteAt string   `form:"complete_at" json:"complete_at"`
}

// TaskCreate 新增任务
func (service *TaskCreateService) TaskCreate(userUID string) *serializer.Response {
	uid := xid.New()
	var excuteUser string
	if len(service.ExecuteBy) != 0 {
		excuteUser = strings.Join(service.ExecuteBy, ",")
	}

	task := model.Task{
		UID:       uid.String(),
		Name:      service.Name,
		ProjectID: service.ProjectID,
		Intro:     service.Intro,
		Status:    service.Status,
		Priority:  service.Priority,
		Progress:  service.Progress,
		Weight:    service.Weight,
		ReviewBy:  service.ReviewBy,
		ExecuteBy: excuteUser,
		CreatedBy: userUID,
	}

	if service.StartAt != "" {
		startAt, _ := time.ParseInLocation("2006-01-02 15:04:05", service.StartAt, time.Local)
		task.StartAt = &startAt
	}

	if service.DeadlineAt != "" {
		deadlineAt, _ := time.ParseInLocation("2006-01-02 15:04:05", service.DeadlineAt, time.Local)
		task.DeadlineAt = &deadlineAt
	}

	if service.Progress == 100 || service.Status == 3 {
		completeAt, _ := time.ParseInLocation("2006-01-02 15:04:05", service.CompleteAt, time.Local)
		task.CompleteAt = &completeAt
	}

	// count := 0
	// model.DB.Model(&model.Task{}).Where("name = ?", service.Name).Count(&count)
	// if count > 0 {
	// 	return &serializer.Response{
	// 		Status: 40001,
	// 		Msg:    "任务名称被占用",
	// 	}
	// }

	// 创建任务
	if err := model.DB.Create(&task).Error; err != nil {
		return &serializer.Response{
			Status: 50001,
			Msg:    "任务保存失败",
			Error:  err.Error(),
		}
	}

	return &serializer.Response{
		Data:   true,
		Msg:    "成功",
		Status: 0,
	}
}
